﻿/*
 * Project: IV:MP GUI Editor (http://code.google.com/p/ivmp-gui-editor)
 * Code license: GNU Lesser GPL (http://www.gnu.org/copyleft/lesser.html)
 * 
 * Authors: CrackHD
 * Description: static class of application config file (which is loaded and in use)
 */

using SmartIni;
using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Collections.Generic;

namespace IvmpEditor
{
    public static class Settings
    {
        static readonly string strConfigFileName = Common.ToAbsolutePath("settings.ini", Common.DirUserAppData);
        static IniFile g_Config;

        public static bool Load()
        {
            if (IsLoaded)
                throw new InvalidOperationException("Config is already loaded.");

            try
            {
                // settings.ini in CommonAppData is "template" for users
                if (!File.Exists(strConfigFileName))
                    File.Copy(Common.ToAbsolutePath("settings.ini", Common.DirCommonAppData), strConfigFileName);

                // Load config file:
                using (var stream = File.Open(strConfigFileName, FileMode.Open, FileAccess.Read))
                    g_Config = Ini.LoadData(new StreamReader(stream, Encoding.Default));
                return true;
            }
            catch
            {
                /*// Create default config FIXME
                g_Config = SmartIni.Ini.LoadData(Common.CreateStreamFromString(
@"[FavoriteEncodings]
CodePage = 1251
CodePage = 12000
CodePage = 1252", 
                Encoding.Default));*/
                g_Config = new IniFile();
                return false;
            }
        }
        public static void Save()
        {
            if (!IsLoaded)
                throw new InvalidOperationException("Config is NOT loaded and cannot be saved!");

            using (var stream = File.Open(strConfigFileName, FileMode.Create, FileAccess.Write))
                 Ini.SaveData(g_Config, new StreamWriter(stream, Encoding.Default));
        }
        public static bool IsLoaded { get { return g_Config != null; } }

        public static Size MainWindowSize
        {
            get { return Size.Parse(g_Config.DefaultNode.Get("MainWindowSize", "952,678")); }
            set { g_Config.DefaultNode.Set("MainWindowSize", value.ToString()); }
        }
        public static Point MainWindowPosition
        {
            get { return Point.Parse(g_Config.DefaultNode.Get("MainWindowPosition", "100,100")); }
            set { g_Config.DefaultNode.Set("MainWindowPosition", value.ToString()); }
        }
        public static bool MainWindowMaximized
        {
            get { return g_Config.DefaultNode.GetBool("MainWindowMaximized", false); }
            set { g_Config.DefaultNode.Set("MainWindowMaximized", value); }
        }
        public static bool MultiTabbedInterface
        {
            get { return g_Config.DefaultNode.GetBool("MultiTabbedInterface", true); }
            set { g_Config.DefaultNode.Set("MultiTabbedInterface", value); }
        }
        public static string LocalizeCulture
        {
            get
            {
                // Installer will set value [Installer]:UsedLanguage to language name which is used during installation
                if (g_Config["Installer"] != null)
                {
                    switch (g_Config["Installer"].Get("UsedLanguage", "Unknown"))
                    {
                        case "English":     g_Config.DefaultNode.Set("LocalizeCulture", "en-gb");
                            break;
                        case "Russian":     g_Config.DefaultNode.Set("LocalizeCulture", "ru-ru");
                            break;
                        case "Hungarian":   g_Config.DefaultNode.Set("LocalizeCulture", "hu-hu");
                            break;
                        case "French":      g_Config.DefaultNode.Set("LocalizeCulture", "fr-fr");
                            break;
                        case "German":      g_Config.DefaultNode.Set("LocalizeCulture", "de-de");
                            break;
                        default:            g_Config.DefaultNode.Set("LocalizeCulture", "auto");
                            break;
                    }
                    g_Config.Nodes.Remove(g_Config["Installer"]);
                }

                return g_Config.DefaultNode.Get("LocalizeCulture", "auto");
            }
            set { g_Config.DefaultNode.Set("LocalizeCulture", value); }
        }
        public static Encoding[] FavoriteEncodings
        {
            get
            {
                var encodings = g_Config["FavoriteEncodings"];
                if (encodings == null)
                    return new Encoding[0];
                //else
                var codePages = encodings.GetValuesList("CodePage");
                var ret = new Encoding[codePages.Count];
                for (var i = 0; i < codePages.Count; i++)
                    ret[i] = Encoding.GetEncoding(int.Parse(codePages[i]));
                return ret;
            }
            set
            {
                var encodings = g_Config["FavoriteEncodings"];
                if (encodings != null)
                {
                    g_Config.Nodes.Remove(encodings);
                    encodings.Values.Clear();
                }
                else
                    encodings = new IniNode("FavoriteEncodings");

                for (var i = 0; i < value.Length; i++)
                    encodings.Values.Add("CodePage", value[i].CodePage.ToString());

                g_Config.Nodes.Add(encodings);
            }
        }
        public static List<string> RecentFiles
        {
            get
            {
                var node = g_Config["Recent files"];
                if (node == null)
                    return null;

                return node.GetValuesList("File");
            }
        }
        public static string PawnIncludesDir
        {
            get { return g_Config.DefaultNode.Get("PawnIncludesDir", "..\\pawno\\include"); }
            set { g_Config.DefaultNode.Set("PawnIncludesDir", value); }
        }
        public static bool RememberWindowState
        {
            get { return g_Config.DefaultNode.GetBool("RememberWindowState", true); }
            set { g_Config.DefaultNode.Set("RememberWindowState", value); }
        }
        public static bool RestoreOpenedTabs
        {
            get { return g_Config.DefaultNode.GetBool("RestoreOpenedTabs", false); }
            set { g_Config.DefaultNode.Set("RestoreOpenedTabs", value); }
        }
        public static string SquirrelEXEName
        {
            set { g_Config.DefaultNode.Set("SquirrelEXEName", value); }
            get { return g_Config.DefaultNode.Get("SquirrelEXEName", SquirrelCompiler.C_DEFAULT_EXE); }
        }

        public static List<string> AddRecentFilesTop(string fileName)
        {
            var node = g_Config["Recent files"];
            if (node == null)
            {
                node = new IniNode("Recent files");
                g_Config.Nodes.Add(node);
                node.Values.Add("File", fileName);
                return RecentFiles;
            }

            var vals = node.GetValuesList("File");
            while (vals.Count > 10)
                vals.RemoveAt(vals.Count - 1);

            if (vals.Contains(fileName))
                vals.Remove(fileName);

            vals.Insert(0, fileName);
            return vals;
        }
    }
}